$(function() {
    // 从全局配置读取服务器地址和认证信息
    const baseUrl = window.appConfig.server.baseUrl;
    const { username, password } = window.appConfig.auth;

    // Token存储和请求状态
    let authToken = null;
    let isRefreshingToken = false;
    const MAX_RETRY_COUNT = 3;

    // DOM元素
    const $loadingIndicator = $('#loadingIndicator');
    const $errorMessage = $('#errorMessage');

    // 通用工具函数
    function showLoading() {
        $loadingIndicator.show();
    }

    function hideLoading() {
        $loadingIndicator.hide();
    }

    function showError(message, duration = 5000) {
        $errorMessage.text(message).show();
        if (duration > 0) {
            setTimeout(() => $errorMessage.hide(), duration);
        }
    }

    function handleError(error, context = '') {
        const errorMsg = `[${context}] ${error.message || error}`;
        console.error(errorMsg, error);
        showError(`操作失败: ${context}`);
        return Promise.reject(error);
    }

    // 登录函数
    function login() {
        if (isRefreshingToken) {
            return Promise.reject('已有正在进行的登录请求');
        }

        isRefreshingToken = true;
        showLoading();

        return new Promise((resolve, reject) => {
            $.ajax({
                url: `${baseUrl}/authenticate`,
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Accept': 'application/json'
                },
                data: JSON.stringify({ username, password }),
                dataType: 'json',
                success: (response) => {
                    if (!response?.token) {
                        throw new Error('无效的响应格式');
                    }
                    authToken = response.token;
                    console.log('登录成功，token已更新');
                    resolve(response.token);
                },
                error: (jqXHR) => {
                    const error = new Error(jqXHR.responseText || '登录失败');
                    error.status = jqXHR.status;
                    reject(error);
                },
                complete: () => {
                    isRefreshingToken = false;
                    hideLoading();
                }
            });
        }).catch(error => handleError(error, '登录'));
    }

    // 带认证的请求函数
    function makeAuthenticatedRequest(url, callback, data = null, method = 'GET', retryCount = MAX_RETRY_COUNT) {
        if (retryCount <= 0) {
            return handleError(new Error('超过最大重试次数'), `请求${url}`);
        }

        const request = () => {
            const requestOptions = {
                url: `${baseUrl}${url}`,
                method,
                headers: {
                    'Authorization': `Bearer ${authToken}`,
                    'Content-Type': 'application/json',
                    'Accept': 'application/json'
                },
                dataType: 'json',
                success: (response) => {
                    try {
                        callback(response);
                    } catch (e) {
                        handleError(e, '回调处理');
                    }
                },
                error: (jqXHR) => {
                    if (jqXHR.status === 401) {
                        login()
                            .then(() => makeAuthenticatedRequest(url, callback, data, method, retryCount - 1))
                            .catch(error => handleError(error, '重新认证'));
                    } else {
                        handleError(new Error(jqXHR.responseText || '请求失败'), `请求${url}`);
                    }
                }
            };

            if (data) {
                requestOptions.data = JSON.stringify(data);
            }

            $.ajax(requestOptions);
        };

        if (!authToken) {
            login().then(request).catch(error => handleError(error, '初始登录'));
        } else {
            request();
        }
    }

    // 主应用函数
    function apiFn() {
        this.hostname = "";
    }

    apiFn.prototype = {
        Init: function() {
            showLoading();
            login()
                .then(() => {
                    this.initializeModules();
                    this.setupIntervals();
                })
                .catch(error => handleError(error, '初始化'))
                .finally(hideLoading);
        },

        initializeModules: function() {
            const modules = [
                'findCount',
                'publicInformation',
                'Policy',
                'otherDataFn',
                'baseInfo',
                'questionFn',
                'publicityFn',
                'threeTasksFn',
                'departmentFn',
                'coverageFn',
                'yearsNumFn',
                'contentFn',
                'publicNumFn'
            ];

            modules.forEach(method => {
                try {
                    if (typeof this[method] === 'function') {
                        this[method]();
                    }
                } catch (e) {
                    handleError(e, `执行${method}`);
                }
            });
        },

        setupIntervals: function() {
            // 初始化计数器（如果存在）
            if (typeof numInit === 'function') {
                setInterval(numInit, 6000);
            }

            // 其他需要定时执行的操作可以在这里添加
        },

        // 各功能模块保持不变
        findCount: function() {
            // 可以添加带token的请求
        },

        otherDataFn: function() {
            makeAuthenticatedRequest('/data1', function(data) {
                if (!data?.data) return;

                const counters = {
                    '.daysData': data.data.daysData,
                    '.weekData': data.data.weekData,
                    '.monthData': data.data.monthData,
                    '.someThing': data.data.someThing,
                    '.policyData': data.data.policyData
                };

                Object.entries(counters).forEach(([selector, value]) => {
                    $(selector).addClass("counter-value").text(value);
                });
            });
        },

        baseInfo: function() {
            makeAuthenticatedRequest('/baseInfo', function(data) {
                if (!data?.data?.length) return;

                try {
                    const chart = echarts.init(document.getElementById('baseId'));
                    const option = this.buildBaseInfoOption(data.data);
                    chart.setOption(option);

                    setInterval(() => {
                        chart.clear();
                        chart.setOption(option);
                    }, 20000);
                } catch (e) {
                    handleError(e, 'baseInfo图表');
                }
            }.bind(this));
        },

        buildBaseInfoOption: function(data) {
            const colors = ['rgba(100,255,249', 'rgba(100,255,249', 'rgba(100,255,249', 'rgba(100,255,249', 'rgba(100,255,249'];

            const seriesData = data.map((item, i) => {
                const colorIndex = Math.min(i, colors.length - 1);
                return {
                    name: item.name,
                    color: colors[colorIndex] + ')',
                    value: item.num,
                    itemStyle: {
                        normal: {
                            show: true,
                            color: new echarts.graphic.LinearGradient(0, 0, 1, 0, [
                                { offset: 0, color: colors[colorIndex] + ', 0.3)' },
                                { offset: 1, color: colors[colorIndex] + ', 1)' }
                            ], false),
                            barBorderRadius: 10
                        },
                        emphasis: {
                            shadowBlur: 15,
                            shadowColor: 'rgba(0, 0, 0, 0.1)'
                        }
                    }
                };
            });

            return {
                title: { show: false },
                grid: {
                    top: '10%',
                    left: '30%',
                    right: '20%',
                    bottom: '3%'
                },
                color: colors,
                yAxis: [{
                    type: 'category',
                    inverse: true,
                    axisTick: { show: false },
                    axisLine: { show: false },
                    axisLabel: { show: false, inside: false },
                    data: data.map(item => item.name)
                }, {
                    type: 'category',
                    inverse: true,
                    axisLine: { show: false },
                    axisTick: { show: false },
                    axisLabel: {
                        show: true,
                        inside: false,
                        textStyle: { color: '#38E1E1', fontSize: '8' },
                        formatter: (val, index) => data[index].num
                    },
                    splitArea: { show: false },
                    splitLine: { show: false },
                    data: data
                }],
                xAxis: {
                    axisTick: { show: false },
                    axisLine: { show: false },
                    splitLine: { show: false },
                    axisLabel: { show: false }
                },
                series: [{
                    name: '',
                    type: 'bar',
                    zlevel: 2,
                    barWidth: '5px',
                    data: seriesData,
                    animationDuration: 1500,
                    label: {
                        normal: {
                            color: 'white',
                            show: true,
                            position: [-65, -2],
                            textStyle: { fontSize: 8 },
                            formatter: params => params.name
                        }
                    }
                }],
                animationEasing: 'cubicOut'
            };
        },

        // 其他模块函数保持原有实现，但添加错误处理
        questionFn: function() {
            makeAuthenticatedRequest('/Problem', function(data) {
                if (!data?.data?.length) return;

                try {
                    const chart = echarts.init(document.getElementById('questionId'));
                    const option = this.buildPieChartOption('问题反馈', data.data, ['#2E8CFF', '#FD9133','#37D2D4','#19CA88','#858FF8']);
                    chart.setOption(option);

                    this.setupChartHighlight(chart, option, 1000);

                    setInterval(() => {
                        chart.clear();
                        chart.setOption(option);
                    }, 8000);
                } catch (e) {
                    handleError(e, 'questionFn图表');
                }
            }.bind(this));
        },

        // 通用饼图配置
        buildPieChartOption: function(title, data, colors) {
            return {
                title: { left: 'center' },
                tooltip: {
                    trigger: 'item',
                    formatter: '{a} <br/>{b} : {c} ({d}%)'
                },
                color: colors,
                legend: {
                    itemWidth: 11,
                    itemHeight: 11,
                    orient: 'vertical',
                    top: '15%',
                    x: '50%',
                    data: data,
                    textStyle: {
                        color: '#fff',
                        fontSize: 8
                    },
                },
                series: [{
                    name: title,
                    type: 'pie',
                    radius: '75%',
                    center: ['20%', '50%'],
                    animationDuration: 2500,
                    data: data,
                    label: {
                        normal: {
                            position: 'inner',
                            show: false
                        }
                    }
                }]
            };
        },

        // 图表高亮逻辑
        setupChartHighlight: function(chart, option, interval) {
            let currentIndex = -1;
            const dataLen = option.series[0].data.length;

            const highlightNext = () => {
                chart.dispatchAction({ type: 'downplay', seriesIndex: 0, dataIndex: currentIndex });
                currentIndex = (currentIndex + 1) % dataLen;
                chart.dispatchAction({ type: 'highlight', seriesIndex: 0, dataIndex: currentIndex });
                chart.dispatchAction({ type: 'showTip', seriesIndex: 0, dataIndex: currentIndex });
            };

            setInterval(highlightNext, interval);
        },

        // 其他模块函数（保持原有结构，但添加错误处理）
        publicityFn: function() {
            makeAuthenticatedRequest('/Career', function(data) {
                if (!data?.data?.length) return;

                try {
                    const chart = echarts.init(document.getElementById('publicityId'));
                    const option = this.buildRingChartOption('四川-成都从业人员职业占比', data.data);
                    chart.setOption(option);

                    this.setupChartHighlight(chart, option, 1000);

                    setInterval(() => {
                        chart.clear();
                        chart.setOption(option);
                    }, 6000);
                } catch (e) {
                    handleError(e, 'publicityFn图表');
                }
            }.bind(this));
        },

        buildRingChartOption: function(title, data) {
            return {
                color: ['#FD9133', '#47F6A2', '#37D2D4', '#3493FF'],
                tooltip: {
                    trigger: 'item',
                    formatter: "{a} <br/>{b} : {c} ({d}%)"
                },
                legend: {
                    itemWidth: 15,
                    itemHeight: 15,
                    orient: 'vertical',
                    top: '30%',
                    bottom: '50%',
                    x: '5%',
                    textStyle: {
                        color: '#fff',
                        fontSize: 8,
                    },
                    data: data,
                },
                series: [
                    {
                        name: title,
                        type: 'pie',
                        radius: ['50%', '70%'],
                        center: ['78%', '52%'],
                        labelLine: {
                            normal: {
                                length: 12,
                                lineStyle: {
                                    type: 'solid',
                                    color: '#0EFCFF'
                                }
                            }
                        },
                        label: {
                            normal: {
                                formatter: params => params.name,
                                borderWidth: 0,
                                borderRadius: 4,
                                padding: [0,0],
                                height: 20,
                                fontSize: 8,
                                align: 'center',
                                color: '#0EFCFF',
                            }
                        },
                        data: data
                    },
                    {
                        color: '#0EFCFF',
                        type: 'pie',
                        radius: ['55', '56'],
                        center: ['78%', '52%'],
                        data: [100],
                        label: { show: false }
                    },
                    {
                        type: 'pie',
                        radius: ['25', '26'],
                        center: ['78%', '52%'],
                        data: [100],
                        label: { show: false }
                    }
                ]
            };
        },

        // 政策信息指南
        publicInformation: function() {
            makeAuthenticatedRequest('/information', function(data) {
                if (!data?.data?.length) return;

                try {
                    const $container = $("#Information");
                    const html = data.data.map((item, index) => `
                        <li>
                            <div class="main_bottom_t_l_main_list">
                                <div class="main_bottom_t_list_title main_bottom_t_list_title${index+1}">
                                    ${item.content}
                                </div>
                                <div class="main_bottom_t_list_time main_bottom_t_list_time${index+1}">
                                    ${item.times.substring(0,9)}
                                </div>
                            </div>
                        </li>
                    `).join('');

                    $container.html(html);

                    $(".main_bottom_t_l_main").jCarouselLite({
                        vertical: true,
                        hoverPause: true,
                        visible: 4,
                        auto: 1000,
                        speed: 500
                    });
                } catch (e) {
                    handleError(e, 'publicInformation');
                }
            });
        },

        // 政策解读
        Policy: function() {
            makeAuthenticatedRequest('/Policy', function(data) {
                if (!data?.data?.length) return;

                try {
                    const $container = $("#Policy");
                    const html = data.data.map((item, index) => `
                        <li>
                            <div class="main_bottom_t_l_main_list">
                                <div class="main_bottom_t_list_title main_bottom_polity_title${index+1}">
                                    ${item.names}
                                </div>
                                <div class="main_bottom_t_list_time main_bottom_polity_time${index+1}">
                                    ${item.times.substring(0,9)}
                                </div>
                            </div>
                        </li>
                    `).join('');

                    $container.html(html);

                    $(".main_bottom_t_l_main2").jCarouselLite({
                        vertical: true,
                        hoverPause: true,
                        visible: 4,
                        auto: 1000,
                        speed: 500
                    });
                } catch (e) {
                    handleError(e, 'Policy');
                }
            });
        },

        // 三务公开数量
        threeTasksFn: function() {
            makeAuthenticatedRequest('/Bigdata', function(data) {
                if (!data?.data) return;

                try {
                    const numbers = data.data.toString().split('');
                    numbers.forEach((num, i) => {
                        $(`.main_top_middle_num_list${i+1}`).text(num);
                    });
                } catch (e) {
                    handleError(e, 'threeTasksFn数字显示');
                }
            });

            makeAuthenticatedRequest('/data2', function(data) {
                if (!data?.data?.length) return;

                try {
                    data.data.forEach((item, i) => {
                        $(`.main_top_left_c_l_n${i+1}`)
                            .addClass("counter-value")
                            .text(item.value);
                    });

                    const chart = echarts.init(document.getElementById('threeTasksId'));
                    const option = this.buildRingChartOption('忘仙谷游客占比', data.data);
                    chart.setOption(option);

                    this.setupChartHighlight(chart, option, 1000);

                    setInterval(() => {
                        chart.clear();
                        chart.setOption(option);
                    }, 10000);
                } catch (e) {
                    handleError(e, 'threeTasksFn图表');
                }
            }.bind(this));
        },

        // 忘仙谷游客占比
        departmentFn: function() {
            makeAuthenticatedRequest('/Tourist', function(data) {
                if (!data?.data?.length) return;

                try {
                    data.data.forEach((item, i) => {
                        $(`.main_list_title_num${i+1}`)
                            .addClass("counter-value")
                            .text(item.value);
                        $(`.main_list_title${i+1}`).text(item.name);
                    });

                    const chart = echarts.init(document.getElementById('departmentId'));
                    const option = this.buildRingChartOption('忘仙谷游客占比', data.data);
                    chart.setOption(option);

                    this.setupChartHighlight(chart, option, 1000);

                    setInterval(() => {
                        chart.clear();
                        chart.setOption(option);
                    }, 22000);
                } catch (e) {
                    handleError(e, 'departmentFn');
                }
            }.bind(this));
        },

        // 主要关注内容区域占比
        coverageFn: function() {
            makeAuthenticatedRequest('/neirong', function(data) {
                if (!data?.data?.length) return;

                try {
                    const indicators = data.data.map(item => ({
                        name: item.name,
                        max: 10000
                    }));

                    const seriesData = [{
                        value: data.data.map(item => item.value)
                    }];

                    const chart = echarts.init(document.getElementById('coverageId'));
                    const option = {
                        legend: {
                            show: true,
                            icon: "circle",
                            bottom: 30,
                            center: 0,
                            itemWidth: 14,
                            itemHeight: 14,
                            itemGap: 21,
                            orient: "horizontal",
                            data: ['a', 'b'],
                            textStyle: {
                                fontSize: '70%',
                                color: '#0EFCFF'
                            },
                        },
                        radar: {
                            radius: '70%',
                            triggerEvent: true,
                            name: {
                                textStyle: {
                                    color: '#39DCF4',
                                    fontSize: '10',
                                    padding: [10, 10]
                                }
                            },
                            nameGap: '2',
                            indicator: indicators,
                            splitArea: {
                                areaStyle: {
                                    color: 'rgba(255,255,255,0)'
                                }
                            },
                            axisLine: {
                                lineStyle: {
                                    color: 'rgba(255,255,255,.2)'
                                }
                            },
                            splitLine: {
                                lineStyle: {
                                    width: 1,
                                    color: 'rgba(255,255,255,.2)'
                                }
                            },
                        },
                        series: [{
                            name: '内容占比',
                            type: 'radar',
                            animationDuration: 1000,
                            areaStyle: {
                                normal: {
                                    color: {
                                        type: 'linear',
                                        opacity: 1,
                                        x: 0,
                                        y: 0,
                                        x2: 0,
                                        y2: 1,
                                        color: '#2EEFAD'
                                    }
                                }
                            },
                            symbolSize: 0,
                            lineStyle: {
                                normal: {
                                    width: 0
                                }
                            },
                            data: seriesData,
                            label: {
                                show: true,
                                position: 'top'
                            }
                        }]
                    };

                    chart.setOption(option);

                    setInterval(() => {
                        chart.clear();
                        chart.setOption(option);
                    }, 20000);
                } catch (e) {
                    handleError(e, 'coverageFn');
                }
            });
        },

        // 舆论公开数量
        yearsNumFn: function() {
            makeAuthenticatedRequest('/opinion', (data) => {
                if (!data?.data?.length) {
                    console.warn('舆论公开数据为空');
                    document.getElementById('yearsNumId').innerHTML =
                        '<div style="color:#fff;text-align:center;padding-top:20px;">暂无舆论数据</div>';
                    return;
                }

                try {
                    const categories = data.data.map(item => item.name).reverse();
                    const seriesData = data.data.map(item => item.value).reverse();

                    const chart = echarts.init(document.getElementById('yearsNumId'));
                    const option = this.buildBarChartOption(categories, seriesData);
                    chart.setOption(option);

                    // 响应式调整
                    const resizeHandler = () => chart.resize();
                    window.addEventListener('resize', resizeHandler);

                    // 定时刷新
                    const refreshInterval = setInterval(() => {
                        chart.clear();
                        chart.setOption(option);
                    }, 120000);

                    // 清理函数
                    this.cleanupYearsNumChart = () => {
                        window.removeEventListener('resize', resizeHandler);
                        clearInterval(refreshInterval);
                        chart.dispose();
                    };

                } catch (e) {
                    handleError(e, 'yearsNumFn图表渲染');
                    document.getElementById('yearsNumId').innerHTML =
                        '<div style="color:#fff;text-align:center;padding-top:20px;">图表加载失败</div>';
                }
            });
        },

        buildBarChartOption: function(categories, seriesData) {
            const _max = 100;
            const formatter = v => (v.value / _max * 100).toFixed(0);

            return {
                grid: {
                    containLabel: true,
                    left: 0,
                    top: 0,
                    right: 0,
                    bottom: 0
                },
                tooltip: {
                    show: true,
                    backgroundColor: '#fff',
                    borderColor: '#ddd',
                    borderWidth: 1,
                    textStyle: {
                        color: '#3c3c3c',
                        fontSize: 16
                    },
                    extraCssText: 'box-shadow: 0 0 5px rgba(0, 0, 0, 0.1)'
                },
                xAxis: {
                    splitNumber: 5,
                    interval: _max / 5,
                    max: _max,
                    axisLabel: {
                        show: false,
                        formatter: v => {
                            const _v = (v / _max * 100).toFixed(0);
                            return _v == 0 ? _v : _v + '%';
                        }
                    },
                    axisLine: { show: false },
                    axisTick: { show: false },
                    splitLine: { show: false }
                },
                yAxis: [{
                    data: categories,
                    axisLabel: {
                        fontSize: 8,
                        color: 'rgba(255,255,255,.7)'
                    },
                    axisLine: { show: false },
                    axisTick: { show: false },
                    splitLine: { show: false }
                }, {
                    show: false,
                    data: categories,
                    axisLine: { show: false }
                }],
                series: [{
                    type: 'bar',
                    name: '数据',
                    stack: '2',
                    label: {
                        normal: {
                            show: true,
                            position: 'inside',
                            formatter: formatter,
                            textStyle: {
                                color: '#fff',
                                fontSize: 8
                            }
                        }
                    },
                    legendHoverLink: false,
                    barWidth: 20,
                    itemStyle: {
                        normal: { color: '#FD9133' },
                        emphasis: { color: '#FD9133' }
                    },
                    data: seriesData
                }]
            };
        },

        // 关注内容区域占比
        contentFn: function() {
            makeAuthenticatedRequest('/data2', (data) => {  // 改为箭头函数
                if (!data?.data?.length) {
                    console.warn('内容区域数据为空');
                    document.getElementById('contentId').innerHTML =
                        '<div style="color:#fff;text-align:center;padding-top:20px;">暂无内容数据</div>';
                    return;
                }

                try {
                    const categories = data.data.map(item => item.name);
                    const seriesData = data.data.map(item => item.value);

                    const chart = echarts.init(document.getElementById('contentId'));
                    const option = this.buildColumnChartOption(categories, seriesData);
                    chart.setOption(option);

                    // 响应式调整
                    const resizeHandler = () => chart.resize();
                    window.addEventListener('resize', resizeHandler);

                    // 清理函数
                    this.cleanupContentChart = () => {
                        window.removeEventListener('resize', resizeHandler);
                        chart.dispose();
                    };

                } catch (e) {
                    handleError(e, 'contentFn图表渲染');
                    document.getElementById('contentId').innerHTML =
                        '<div style="color:#fff;text-align:center;padding-top:20px;">图表加载失败</div>';
                }
            });
        },

        buildColumnChartOption: function(categories, seriesData) {
            return {
                tooltip: { trigger: 'axis' },
                legend: {
                    x: '10%',
                    y: '0%',
                    data: categories,
                    textStyle: {
                        color: "#fff",
                        fontSize: 8
                    },
                    itemWidth: 10,
                    itemHeight: 10,
                },
                calculable: true,
                xAxis: [{
                    type: 'category',
                    data: categories,
                    axisLabel: {
                        interval: 0,
                        textStyle: {
                            fontSize: 8,
                            color: 'rgba(255,255,255,.7)',
                        }
                    },
                    axisTick: { show: false },
                    axisLine: { show: false },
                }],
                yAxis: [{
                    type: 'value',
                    scale: true,
                    name: '单位：件',
                    nameTextStyle: {
                        color: 'rgba(255,255,255,.7)',
                        fontSize: 8
                    },
                    max: 2000,
                    min: 0,
                    boundaryGap: [0.2, 0.2],
                    axisTick: { show: false },
                    axisLine: { show: false },
                    axisLabel: {
                        textStyle: {
                            color: 'rgba(255,255,255,.8)',
                            fontSize: 8
                        }
                    },
                    splitLine: {
                        show: true,
                        lineStyle: {
                            color: ['#fff'],
                            opacity: 0.2
                        }
                    },
                }],
                color: ['#0EFCFF'],
                grid: {
                    left: '5%',
                    right: '1%',
                    top: '25%',
                    bottom: '15%'
                },
                series: [{
                    barWidth: '20%',
                    type: 'bar',
                    data: seriesData,
                    label: {
                        show: true,
                        position: 'top'
                    }
                }]
            };
        },

        // 就业统计
        publicNumFn: function() {
            makeAuthenticatedRequest('/Employment', function(data) {
                // 严格检查接口数据
                if (!Array.isArray(data?.data) || data.data.length === 0) {
                    console.error('就业数据接口返回空或无效数据');
                    document.getElementById('EmploymentId').innerHTML =
                        '<div style="color:#fff;text-align:center;padding-top:20px;">暂无就业数据</div>';
                    return;
                }

                try {
                    // 处理接口数据
                    const categories = data.data.map(item => item.name || '');
                    const values = data.data.map(item => Number(item.value) || 0);

                    // 计算动态Y轴最大值（增加20%余量）
                    const maxValue = Math.max(...values) * 1.2;

                    // 初始化图表
                    const chart = echarts.init(document.getElementById('EmploymentId'));

                    // 图表配置
                    const option = {
                        title: {
                            text: '就业情况统计',
                            left: 'center',
                            textStyle: {
                                color: '#fff',
                                fontSize: 12
                            }
                        },
                        tooltip: {
                            trigger: 'axis',
                            formatter: params => {
                                return `${params[0].axisValue}<br/>
                        就业人数: ${params[0].data}`;
                            }
                        },
                        legend: {
                            show: false
                        },
                        xAxis: {
                            type: 'category',
                            data: categories,
                            axisLabel: {
                                interval: 0,
                                fontSize: 8,
                                color: 'rgba(255,255,255,.7)',
                                rotate: categories.length > 6 ? 30 : 0  // 数据多时旋转标签
                            },
                            axisTick: { show: false },
                            axisLine: { show: false },
                        },
                        yAxis: {
                            type: 'value',
                            name: '就业人数',
                            nameTextStyle: {
                                color: 'rgba(255,255,255,.7)',
                                fontSize: 8
                            },
                            max: maxValue,
                            min: 0,
                            axisTick: { show: false },
                            axisLine: { show: false },
                            axisLabel: {
                                fontSize: 8,
                                color: 'rgba(255,255,255,.8)'
                            },
                            splitLine: {
                                lineStyle: {
                                    color: 'rgba(255,255,255,.1)'
                                }
                            }
                        },
                        grid: {
                            left: '12%',
                            right: '5%',
                            top: '20%',
                            bottom: categories.length > 6 ? '25%' : '15%'
                        },
                        series: [{
                            name: '就业人数',
                            type: 'bar',
                            barWidth: '60%',
                            data: values,
                            itemStyle: {
                                color: new echarts.graphic.LinearGradient(
                                    0, 0, 0, 1,
                                    [
                                        { offset: 0, color: '#2E8CFF' },
                                        { offset: 1, color: '#37D2D4' }
                                    ]
                                )
                            },
                            label: {
                                show: true,
                                position: 'top',
                                fontSize: 8,
                                color: '#fff',
                                formatter: '{c}'
                            }
                        }]
                    };

                    // 应用配置
                    chart.setOption(option);

                    // 响应式调整
                    const resizeHandler = () => chart.resize();
                    window.addEventListener('resize', resizeHandler);

                    // 定时刷新数据
                    let refreshInterval = setInterval(() => {
                        this.publicNumFn(); // 重新调用方法获取最新数据
                    }, 300000); // 5分钟刷新一次

                    // 清理函数（根据实际场景调用）
                    this.cleanupEmploymentChart = () => {
                        window.removeEventListener('resize', resizeHandler);
                        clearInterval(refreshInterval);
                        chart.dispose();
                    };

                } catch (e) {
                    handleError(e, '就业数据图表渲染');
                    document.getElementById('EmploymentId').innerHTML =
                        '<div style="color:#fff;text-align:center;padding-top:20px;">图表渲染失败</div>';
                }
            }, null, 'GET', 3); // 最大重试3次
        }

    };

    // 初始化应用
    try {
        const start = new apiFn();
        start.Init();
    } catch (e) {
        handleError(e, '应用初始化');
    }
});